package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

//    @Autowired
//    private JwtProperties jwtProperties;
//
//    @Autowired
//    private HttpServletRequest request;


    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */

    @Override
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //将密码进行md5加密然后进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     *
     * @param employeeDTO
     */
    @Override
    public void insert(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        //框架提供的BeanUtils工具类进行属性值的拷贝
        BeanUtils.copyProperties(employeeDTO, employee);
        //补全剩下的属性值
        employee.setStatus(StatusConstant.ENABLE);
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        //创建时间，修改时间

        /*因为设置了自动的公共字段填充故此处对于公共字段的赋值将被注释掉*/
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        //创建人，修改人


//        String token = request.getHeader(jwtProperties.getAdminTokenName());
//        log.info("jwt校验:{}", token);
//        Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
//        Long empId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());

        /*获取当前ThreadLocal(线程局部变量)中存储的登录的员工的 id值
         * 用上面自己写的方法也可以实现
         * */

//        Long empId = BaseContext.getCurrentId();
//        log.info("当前操作员工id：", empId);
//        employee.setCreateUser(empId);
//        employee.setUpdateUser(empId);

        employeeMapper.insert(employee);
    }

    /**
     * 对员工的条件分页查询
     *
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        List<Employee> employeeList = employeeMapper.pageQuery(employeePageQueryDTO);
        Page<Employee> employeePages = (Page<Employee>) employeeList;
        return new PageResult(employeePages.getTotal(), employeePages.getResult());
    }


    /**
     * 改变员工账号的状态，启用或者禁用
     *
     * @param status
     * @param id
     */
    @Override
    public void changeStatus(Integer status, Long id) {
        Employee employee = Employee.builder().id(id).status(status).build();
        employeeMapper.update(employee);
    }

    /**
     * 修改员工时的查询回显
     *
     * @param id
     * @return
     */
    @Override
    public Employee selectEmployeeById(Long id) {
        Employee employee = employeeMapper.selectEmployeeById(id);
        return employee;
    }

    /**
     * 修改员工
     *
     * @param employeeDTO
     */
    @Override
    public void updateEmployee(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();

        BeanUtils.copyProperties(employeeDTO, employee);
//        employee.setUpdateUser(BaseContext.getCurrentId());
//        employee.setUpdateTime(LocalDateTime.now());
        //直接使用更改状态时候写的的update方法
        employeeMapper.update(employee);
    }

    /**
     * 修改密码
     * @param passwordEditDTO
     */
    @Override
    public void editPassword(PasswordEditDTO passwordEditDTO) {
        //检查原密码和数据库的密码是否相同
        Long currentId = BaseContext.getCurrentId();
        Employee employee = employeeMapper.selectEmployeeById(currentId);
        String passwordInDataBase = employee.getPassword();
        String oldPassword = DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes());
        //相同则修改密码
        if (oldPassword.equals(passwordInDataBase)){
            employee.setPassword(DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes()));
            employeeMapper.update(employee);
        }
        //不同则抛出异常
        else {
            throw new PasswordErrorException(MessageConstant.PASSWORD_EDIT_FAILED);
        }

    }

}
